/*
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-11-01 14:23:34
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2025-03-12 20:41:21
 */
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
const chooseLocation = requirePlugin('chooseLocation');
import {
  showMsg
} from '../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../utils/validate.js'
import {
  reqSpaceAdd,
  reqRegion,
  reqRegionLevel,
  reqOrgList
} from '../../../../request/api'


var QQMapWX = require('../../../../utils/qqmap-wx-jssdk.min'); //地址转经纬度
// 实例化API核心类
var qqmapsdk = new QQMapWX({ //地址转经纬度
  key: '6YRBZ-CE263-TES33-YGBKX-AJ2SH-I4FJH' // 必填,申请的key
})

Page({
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    rolename: '',
    parkId: '', //园区id
    form: {
      name: '',
      lng: '',
      lat: '',
      region: '',
      province: '',
      provinceCode: '',
      city: '',
      cityCode: '',
      area: '',
      areaCode: '',
      street: '',
      streetCode: '',
      community: '',
      communityCode: '',
      address: '',
      isDefence: true,
      buildingType: '', //建筑物性质
      buildingTypeText: '',
      metaCode: 1, //空间类型 
      childrenName: [], //批量新增下级空间名称
      village: "",
      orgId: "",
      orgName: ""
    },
    showUnitSelection: false, //是否展示单位选择弹窗
    provinceList: [], //省列表
    cityList: [], //市列表
    areaList: [], //区列表
    streetList: [], //街道列表
    communityList: [], //社区列表
    showorg: false,
    orgList: [],
    showprovince: false, //省弹窗
    showcity: false, //市弹窗
    showarea: false, //区弹窗
    showStreet: false, //是否展示街道弹窗
    showCommunity: false, //是否展示社区弹窗
    buildingTypeList: [{
        id: 1,
        text: "住宅",
      },
      {
        id: 2,
        text: "旅店",
      },
      {
        id: 3,
        text: "公司",
      },
      {
        id: 4,
        text: "出租屋",
      },
      {
        id: 5,
        text: "餐饮",
      },
      {
        id: 6,
        text: "商店",
      },
      {
        id: 7,
        text: "医院",
      },
      {
        id: 8,
        text: "娱乐场所",
      },
      {
        id: 9,
        text: "生产加工企业和仓库",
      },
      {
        id: 10,
        text: "爱心屋",
      },
      {
        id: 11,
        text: "充电桩",
      },
      {
        id: 99,
        text: "其他",
      }
    ],
    showBuildingType: false, //是否展示建筑物性质弹窗
    radio: "1", //单个添加/批量添加
    floorName: '', //单个添加楼层名称
    batchNameList: [{
      id: 0,
      start: '',
      end: ''
    }, ], //批量添加
    disabledBtn: false,
    apporgId: "", //==1为全部单位
  },
  onLoad(e) {
    this.setData({
      rolename: app.globalData.rolename
    })
    this.getParkId(e)
  },
  onShow() {
    // this.setData({
    //     apporgId: app.globalData.orgId
    // })
    this.getLocation() //获取地图地址信息
    this.Region()
    // this.getOrgList()
  },
  // 单位选择弹窗打开
  onUnitSelection() {
    this.setData({
      showUnitSelection: true
    })
  },
  confirmUnitSelection(e) {
    const {
      showUnitSelection,
      orgInfo
    } = e.detail
    this.setData({
      showUnitSelection,
    })
    if (orgInfo && orgInfo.id) {
      this.setData({
        "form.orgId": orgInfo.id,
        "form.orgName": orgInfo.orgName,
      })
    }
  },

  // 获取单位id
  getParkId(e) {
    if (e.orgId) {
      this.setData({
        "form.orgId": e.orgId,
        'form.orgName': e.orgName,
        apporgId: ""
      })
    } else {
      this.setData({
        "form.orgId": '',
        apporgId: 1
      })
    }
    console.log(this.data.form.orgId, 'orgId');
  },
  // 获取组织列表
  async getOrgList() {
    let params = {
      tenantId: app.globalData.tenantId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
    }
    const res = await reqOrgList(1, 99, params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    console.log(rows);
    this.setData({
      orgList: rows
    })
  },
  // 查询省级行政单位
  async Region() {
    const res = await reqRegion()
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res);
    this.setData({
      provinceList: res.data.rows
    })
  },

  // 获取名称
  nameChange(e) {
    this.data.form.name = validateEmoji(e.detail.value.replace(/\s+/g, ''))
    this.setData({
      "form.name": this.data.form.name
    })
  },
  // 清除名称
  clearName() {
    this.setData({
      "form.name": ''
    })
  },
  // 获取小区名称
  villageChange(e) {
    this.data.form.village = validateEmoji(e.detail.value.replace(/\s+/g, ''))
    this.setData({
      "form.village": this.data.form.village
    })
  },
  // 清除名称
  clearVillage() {
    this.setData({
      "form.village": ''
    })
  },
  // 省市区选择获取
  bindRegionChange(e) {
    this.setData({
      "form.region": e.detail.value,
    });
  },
  //点击腾讯地图选点获取位置
  getLocationClick() {
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    // wgs84   gcj02
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: false, //开启高精度定位
      success(res) {
        console.log(res);
        wx.hideLoading()
        const key = '44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53'; //使用在腾讯位置服务申请的key
        const referer = '精卫安'; //调用插件的app的名称
        const location = JSON.stringify({
          latitude: res.latitude,
          longitude: res.longitude
        });
        const category = '生活服务,娱乐休闲，公司企业';
        wx.navigateTo({
          url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
        });
      },
      fail(err) {
        console.log(err);
        wx.showToast({
          title: '定位失败,请在微信小程序设置中>位置信息>打开定位功能',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },
  // 依据腾讯地图选点获取位置
  getLocation() {
    const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
    if (location !== null) {
      console.log(location);
      this.setData({
        // "form.lng": location.longitude,
        // "form.lat": location.latitude,
        "form.region": location.province + location.city + location.district,
        "form.province": location.province || location.name, //省
        "form.city": location.city, //市
        "form.area": location.district, //区
        "form.address": location.name,
      })
      this.getProvince(location)
    }
  },

  // 获取省级编码
  async getProvince(location) {
    wx.showLoading({
      title: '加载中',
      mask: true,
    })

    const res = await reqRegion()
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    let data = ''
    rows.forEach(item => {
      if (item.regionName === this.data.form.province) {
        data = item
      }
    })
    this.setData({
      'form.provinceCode': data.regionCode
    })
    this.getCity(location, data.regionCode)
  },
  // 获取市级编码
  async getCity(location, code) {
    const res = await reqRegionLevel(code)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    console.log(rows);
    this.setData({
      cityList: rows
    })
    let data = ''
    rows.forEach(item => {
      if (item.regionName === location.city) {
        data = item
      }
    })
    // 市辖区查不到  默认选择第一个  
    if (data == "") {
      this.setData({
        'form.city': rows[0].regionName,
        'form.cityCode': rows[0].regionCode,
        // 'form.street': ""
      })
      // wx.hideLoading()
      // return;
    } else {
      this.setData({
        'form.cityCode': data.regionCode
      })
    }
    this.getArea(location, data.regionCode || rows[0].regionCode)
  },
  // 获取区级编码
  async getArea(location, code) {
    const res = await reqRegionLevel(code)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    let data = ''
    this.setData({
      areaList: rows
    })
    rows.forEach(item => {
      if (item.regionName === location.district) {
        data = item
      }
    })
    // 市辖区查不到  清空  
    if (data == "") {
      this.setData({
        'form.area': "",
        'form.street': ""
      })
      wx.hideLoading()
      return;
    }
    this.setData({
      'form.areaCode': data.regionCode
    })
    this.getStreet(data.regionCode)
  },
  // 获取街道
  async getStreet(code) {
    const res = await reqRegionLevel(code)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    this.setData({
      streetList: rows,
      'form.street': "",
      'form.community': "",
      showStreet: true
    })
    await this.geocoder(this.data.form.province + this.data.form.city + this.data.form.area + this.data.form.street)
    wx.hideLoading()
  },
  // 弹出省
  showprovinceClick() {
    this.setData({
      showprovince: true
    })
  },
  // 关闭省弹窗
  provinceClose() {
    this.setData({
      showprovince: false
    })
  },
  // 弹出市
  showcityClick() {
    this.setData({
      showcity: true
    })
  },
  // 关闭市弹窗
  cityClose() {
    this.setData({
      showcity: false
    })
  },
  // 弹出区
  showareaClick() {
    this.setData({
      showarea: true
    })
  },
  // 关闭区弹窗
  areaClose() {
    this.setData({
      showarea: false
    })
  },
  // 关闭街道弹窗
  streetClose() {
    this.setData({
      showStreet: false
    })
  },
  // 弹出街道
  showStreetClick() {
    this.setData({
      showStreet: true
    })
  },
  // 关闭社区弹窗
  communityClose() {
    this.setData({
      showCommunity: false
    })
  },
  // 弹出社区
  showCommunityClick() {
    this.setData({
      showCommunity: true
    })
  },
  // 省确认
  provinceConfirm(e) {
    console.log(e);
    let location = {
      province: e.detail.value.regionName,
    }
    this.setData({
      "form.province": e.detail.value.regionName, //省
      showprovince: false
    })
    this.getProvince(location)
  },
  // 市确认
  cityConfirm(e) {
    let location = {
      city: e.detail.value.regionName,
    }
    this.setData({
      "form.city": e.detail.value.regionName, //市
      showcity: false
    })
    this.getCity(location, this.data.form.provinceCode)
  },
  // 区确认
  areaConfirm(e) {
    let location = {
      district: e.detail.value.regionName,
    }
    this.setData({
      "form.area": e.detail.value.regionName, //区
      'form.street': "",
      showarea: false
    })
    this.getArea(location, this.data.form.cityCode)
  },
  // 街道确认
  async streetConfirm(e) {
    console.log(e);
    const {
      value,
    } = e.detail;
    this.setData({
      'form.streetCode': value.regionCode,
      'form.street': value.regionName,
      'form.communityCode': '',
      'form.community': '',
    })
    this.streetClose()
    // 获取社区列表
    const res = await reqRegionLevel(value.regionCode)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    this.setData({
      communityList: rows,
    })
    await this.geocoder(this.data.form.province + this.data.form.city + this.data.form.area + this.data.form.street)
  },
  async communityConfirm(e) {
    console.log(e);
    const {
      value,
    } = e.detail;
    this.setData({
      'form.communityCode': value.regionCode,
      'form.community': value.regionName,
    })
    this.communityClose()
  },
  // 获取详细地址
  addressChange(e) {
    this.setData({
      "form.address": e.detail.value
    })
  },
  // 清除详细地址
  clearAddress() {
    this.setData({
      "form.address": ''
    })
  },

  // 弹出建筑物性质
  clickBuildingType() {
    this.setData({
      showBuildingType: true
    })
  },
  // 隐藏建筑物性质
  buildingTypeClose() {
    this.setData({
      showBuildingType: false
    })
  },
  // 确定建筑物性质
  buildingTypeConfirm(e) {
    const {
      value,
      index
    } = e.detail;
    this.setData({
      "form.buildingType": value.id,
      "form.buildingTypeText": value.text,
      showBuildingType: false,
    })
  },

  // 点击布撤防
  changeDefence(e) {
    let tip = e.detail ? '此操作将开启该建筑物所有设备布防设置，是否继续？' : '此操作将关闭该建筑物所有设备布防设置，是否继续？'
    Dialog.confirm({
        title: '温馨提示',
        message: tip,
      })
      .then(async () => {
        this.setData({
          "form.isDefence": e.detail
        })
      })
      .catch(() => {});
  },

  // 选择单个添加/批量添加
  radioChange(e) {
    this.setData({
      radio: e.detail
    })
  },
  // 单个添加获取名称
  floorNameChange(e) {
    // 正则表达式
    let value = e.detail.value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value = value.replace(/\-{2,}/g, "-"); // -只能保留一个
    value = value.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value = value.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value = value.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value > 50) {
      value = 50
    }
    if (value < -3) {
      value = -3
    }
    if (value == '0') {
      value = 1
    }

    // let value = this.validateNumber(e.detail.value)
    this.setData({
      floorName: value
    })
  },
  validateNumber(val) {
    return val.replace(/\D/g, '')
  },
  // 单个添加清除
  clearfloorName() {
    this.setData({
      floorName: ''
    })
  },
  // 点击新增一条楼层段
  clickAddFloor() {
    let {
      batchNameList
    } = this.data
    if (batchNameList.length > 1) return Toast('最多只允许添加两个楼层信息');
    let id = batchNameList.length === 0 ? 0 : batchNameList[batchNameList.length - 1].id + 1
    batchNameList.push({
      id,
      start: '',
      end: ''
    })
    this.setData({
      batchNameList
    })
  },
  // 获取开始层数
  floorStartChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    console.log(value);
    let {
      batchNameList
    } = this.data
    // 正则表达式
    let value2 = value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value2 = value2.replace(/\-{2,}/g, "-"); // -只能保留一个
    value2 = value2.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value2 = value2.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value2 = value2.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value2 > 49) {
      value2 = 49
    }
    if (value2 < -3) {
      value2 = -3
    }
    if (value2 == '0') {
      value2 = 1
    }
    batchNameList.forEach(item => {
      if (item.id === id) {
        item.start = value2
      }
    })
    this.setData({
      batchNameList
    })
  },

  // 获取结束层数
  floorEndeChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    console.log(value);
    let {
      batchNameList
    } = this.data
    // 正则表达式
    let value2 = value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    value2 = value2.replace(/\-{2,}/g, "-"); // -只能保留一个
    value2 = value2.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    value2 = value2.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    value2 = value2.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    if (value2 > 50) {
      value2 = 50
    }
    if (value2 < -3) {
      value2 = -3
    }
    if (value2 == '0') {
      value2 = 1
    }
    batchNameList.forEach(item => {
      if (item.id === id) {
        item.end = value2
      }
    })
    this.setData({
      batchNameList
    })
  },
  // 删除一条
  deleteBatchName(e) {
    let {
      id
    } = e.target.dataset
    let {
      batchNameList
    } = this.data
    batchNameList.splice(id, 1)
    batchNameList.forEach((item, index) => {
      item.id = index
    })
    this.setData({
      batchNameList
    })
  },
  // 地址转经纬度
  geocoder(address) {
    console.log(address);
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: address, //地址
      success: (res) => { //成功后的回调
        console.log(res.result.location.lng, '成功后的回调')
        console.log(res.result.location.lat, '成功后的回调')
        this.setData({
          "form.lng": res.result.location.lng,
          "form.lat": res.result.location.lat,
        })
      },
      fail: function (error) {
        console.error(error, 'error的回调');
      },
      complete: function (res) {
        console.log(res, 'complete的回调');
      }
    })
  },

  // 确认新增建筑物
  async confirm() {
    if (this.data.disabledBtn) return
    let {
      radio,
      floorName,
      batchNameList,
      form
    } = this.data
    console.log(form);
    if (!(form.orgId)) return showMsg("请选择单位")
    if (!(form.name)) return showMsg("请输入名称")
    if (!(form.areaCode)) return showMsg("请选择地区")
    if (!(form.province)) return showMsg("请选择省")
    if (!(form.city)) return showMsg("请选择市")
    if (!(form.area)) return showMsg("请选择区")
    if (!(form.street)) return showMsg("请选择街道")
    if (!(form.address)) return showMsg("请输入详细地址")
    if (!(form.buildingType)) return showMsg("请选择建筑物性质")
    if (!validateSpecial(form.name)) return

    await this.geocoder(this.data.form.province + this.data.form.city + this.data.form.area + this.data.form.street)
    let params = {
      orgId: form.orgId,
      pid: '0',
      name: form.name,
      lng: form.lng,
      lat: form.lat,
      province: form.province,
      provinceCode: form.provinceCode,
      city: form.city,
      cityCode: form.cityCode,
      area: form.area,
      areaCode: form.areaCode,
      street: form.street,
      streetCode: form.streetCode,
      community: form.community,
      communityCode: form.communityCode,
      address: form.address,
      isDefence: form.isDefence ? 1 : 0,
      buildingType: form.buildingType,
      metaCode: form.metaCode,
      childrenName: [],
      picList: [],
      village: form.village
    }

    if (radio == 1) {
      if (!validateSpecial(floorName)) return
      if (floorName) {
        params.childrenName[0] = floorName + '层'
      }
      this.reqSpaceAddFun(params)
    } else if (radio == 2) {
      let arr = []
      let flag = false
      let flag1 = false
      let index = 0
      let index1 = 0
      try {
        batchNameList.forEach(item => {
          if (item.start > item.end) {
            index = item.id + 1
            flag = true
            throw new console.log(`第${index}项错误`);
          }
          if (item.start === '') {
            flag1 = true
            index1 = item.id + 1
            throw new console.log(`第${index1}项错误`);
          }
          for (let i = item.start; i <= item.end; i++) {
            if (i != 0) {
              arr.push(`${i}层`)
            }
          }
        })
      } catch (e) {
        console.log(e);
      }
      if (flag) return showMsg(`第${index}项结束楼层小于开始楼层，请检查！`)
      if (flag1) return showMsg(`第${index1}项开始楼层数未填写，请检查！`)
      params.childrenName = Array.from(new Set(arr));
      params.childrenName.forEach((item, index) => {
        if (!item) {
          params.childrenName.splice(index, 1)
        }
      })
      if (!params.childrenName[0]) return showMsg("请输入")
      if (params.childrenName.length > 50) return showMsg("一次最多添加50个楼层")
      this.reqSpaceAddFun(params)
    } else {
      this.reqSpaceAddFun(params)
    }

  },

  async reqSpaceAddFun(params) {
    const res = await reqSpaceAdd(params)
    if (res.code != 20000) return showMsg(res.message)
    showMsg("新增成功", "success")
    this.setData({
      disabledBtn: true
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 2000)
  },
  // 弹出单位
  showorgClick() {
    this.setData({
      showorg: true
    })
  },
  // 关闭单位
  orgClose() {
    this.setData({
      showorg: false
    })
  },
  // 单位确认
  orgConfirm(e) {
    console.log(e);
    this.setData({
      "form.orgId": e.detail.value.id,
      "form.orgName": e.detail.value.orgName,
      showorg: false
    })
  },
  onUnload() {
    // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
    chooseLocation.setLocation(null);
  },

})